package com.common.www.controller.tabulation;


import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.project.XfgcBiddingCompany;
import com.common.www.bean.entity.tabulation.XfgcBidBaseTabulation;
import com.common.www.bean.entity.tabulation.XfgcTabulation;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.project.XfgcBiddingCompanyService;
import com.common.www.service.tabulation.*;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.office.ImportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/xfgcTabulation"})
@Api(tags = "MGT 后台消防工程供应商清单管理")
public class MGTXfgcTabulationController extends DefaultCrudController<XfgcTabulation, Long> {

    @Autowired
    private XfgcTabulationService xfgcTabulationService;
    @Autowired
    private XfgcBidBaseTabulationService xfgcBidBaseTabulationService;
    @Autowired
    private XfgcBiddingCompanyService biddingCompanyService;
    @Autowired
    private XfgcSummaryService xfgcSummaryService;

    protected IBaseService<XfgcTabulation, Long> getService() {
        return xfgcTabulationService;
    }


    @ApiOperation("保存一条清单数据")
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(@RequestBody XfgcTabulation tabulation) {
        if (tabulation.getId() != null) {
            xfgcTabulationService.calculation(tabulation);
            xfgcTabulationService.save(tabulation);
        }
        return R.ok(tabulation);
    }


    @ApiOperation("编辑综合单价横向对比-差异备注")
    @RequestMapping(value = "/saveByChaYiRemark", method = RequestMethod.POST)
    public Result saveByChaYiRemark(Long id, String chaYiRemark) {
        if (id != null) {
            XfgcTabulation tabulation = xfgcTabulationService.findOne(id);
            tabulation.setChaYiRemark(chaYiRemark);
            xfgcTabulationService.calculation(tabulation);
            xfgcTabulationService.save(tabulation);
        }
        return R.ok();
    }

    @ApiOperation("批量删除（逻辑删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids) {
        if (ParamsUtils.isInputEmpty(ids)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        xfgcTabulationService.deleteByIdsLogic(ids);
        return R.ok();
    }

    @ApiOperation("按项目删除对应标底信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "bidType", value = "String", defaultValue = ""),
    })
    @Transactional
    @RequestMapping(value = "/deletesByBiddingCompanyToType", method = RequestMethod.POST)
    public Result deletesByProjectToType(Long biddingCompanyId, Integer jieDuan) {
        if (ParamsUtils.isInputEmpty(biddingCompanyId, jieDuan)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        XfgcBiddingCompany biddingCompany = biddingCompanyService.findOne(biddingCompanyId);
        xfgcTabulationService.getRepository().deleteByXfgcBiddingCompanyIdAndJieDuan(biddingCompanyId, jieDuan);
        xfgcSummaryService.getRepository().deleteByProjectIdAndJieDuanAndXfgcBiddingCompanyId(biddingCompany.getProject().getId(), jieDuan, biddingCompany.getId());
        return R.ok();
    }


    @ApiOperation(value = "导入供应商清单", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/importQd", produces = {"application/json"}, method = RequestMethod.POST)
    public Result importQd(MultipartFile file, Long biddingCompanyId, Integer jieDuan) throws Exception {
        XfgcBiddingCompany biddingCompany = biddingCompanyService.findOne(biddingCompanyId);
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook workbook = new ImportExcelUtil().getWorkbook(inputStream, fileName);
        List<XfgcTabulation> listImport = xfgcTabulationService.importSimulate(workbook);
        //整理listImport的数据格式
        List<XfgcTabulation> listArrange = new ArrayList<>();

        String itemName = null;
        String lastNonNullOriginalTypeName = null;
        String zbTwo = null;
        String codeNumberType = null;
        for (XfgcTabulation listObj : listImport) {
            String originalTypeName = listObj.getName();
            String currentCodeNumber = listObj.getCodeNumber();
            if (StringUtils.isNotEmpty(currentCodeNumber) && ("HZ".equals(currentCodeNumber) || "GB".equals(currentCodeNumber) || "XHS".equals(currentCodeNumber)
                    || "PL".equals(currentCodeNumber) || "YY".equals(currentCodeNumber) || "MHQ".equals(currentCodeNumber)
                    || "JL".equals(currentCodeNumber) || "QT".equals(currentCodeNumber) || "FHM".equals(currentCodeNumber)
                    || "DYJK".equals(currentCodeNumber) || "HZJK".equals(currentCodeNumber) || "YJZM".equals(currentCodeNumber)
                    || "LX".equals(currentCodeNumber) || "XFJC".equals(currentCodeNumber) || "KZZJ".equals(currentCodeNumber)
                    || "WB".equals(currentCodeNumber) || "ZB".equals(currentCodeNumber))) {
                codeNumberType = currentCodeNumber;
                lastNonNullOriginalTypeName = originalTypeName;
                if ("ZB".equals(currentCodeNumber)) {
                    itemName = originalTypeName;
                }
            } else {
                if (lastNonNullOriginalTypeName != null && "增补清单".equals(itemName)) {
                    //增补清单的下一级
                    if (listObj.getCodeNumber() != null && listObj.getCodeNumber().length() > 2
                            && listObj.getCodeNumber().charAt(0) == 'Z' && listObj.getCodeNumber().charAt(1) == 'B'
                            && !listObj.getCodeNumber().matches(".*[0-9-].*")) {
                        zbTwo = listObj.getName();
                    } else {
                        listObj.setNameType1(itemName);
                        listObj.setNameType2(zbTwo);
                    }
                } else {
                    listObj.setNameType1(lastNonNullOriginalTypeName);
                }
                if (currentCodeNumber != null && !currentCodeNumber.isEmpty() && currentCodeNumber.contains("-")) {
                    listObj.setFlag(1);
                    listObj.setXfgcBiddingCompany(biddingCompany);
                    listObj.setJieDuan(jieDuan);
                    listObj.setCodeNumberType(codeNumberType);
                    listArrange.add(listObj);
                }
            }
        }

        //计算 税金、综合单价
        for (XfgcTabulation tabulation : listArrange) {
            XfgcTabulation tabulationResult = xfgcTabulationService.calculation(tabulation);
        }

        if (listArrange.size() > 0) {
            //先删除原来的，再添加
            List<XfgcTabulation> tabulationList = xfgcTabulationService.getRepository().findByFlagAndXfgcBiddingCompanyIdAndJieDuan(1, biddingCompanyId, jieDuan);
            for (XfgcTabulation tabulation : tabulationList) {
                tabulation.setFlag(0);
                xfgcTabulationService.save(tabulation);
            }
            if (tabulationList.size() > 0) {
                xfgcSummaryService.getRepository().deleteByProjectIdAndJieDuanAndXfgcBiddingCompanyId(tabulationList.get(0).getXfgcBiddingCompany().getProject().getId(), jieDuan, biddingCompanyId);
            }

        }
        xfgcTabulationService.save(listArrange);
        //清单关联信息保存
        xfgcSummaryService.saveCorrelationGys(biddingCompany, jieDuan, fileName);
        return R.ok();
    }


    @ApiOperation("导出供应商清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportXfgcQd", method = RequestMethod.GET)
    public Result exportXfgcQd(Long biddingCompanyId, Integer jieDuan) {
        XfgcBiddingCompany biddingCompany = biddingCompanyService.findOne(biddingCompanyId);
        String bidTypeStr = "";
        if (jieDuan == 2) {
            bidTypeStr = "回标1";
        } else if (jieDuan == 3) {
            bidTypeStr = "回标2";
        } else if (jieDuan == 4) {
            bidTypeStr = "回标3";
        } else if (jieDuan == 5) {
            bidTypeStr = "定标";
        }
        String fileName = biddingCompany.getSupplyCompany().getName() + bidTypeStr;
        XSSFWorkbook workbook = xfgcTabulationService.exportQd(biddingCompanyId, jieDuan, fileName);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


    @ApiOperation(value = "查询清单信息(按分项查询)", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getXfgcTabList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getXfgcTabList(Long xfgcBiddingCompanyId, Integer jieDuan) {
        HashMap hashMap = new HashMap();
        hashMap.put("xfgcBiddingCompany.id", xfgcBiddingCompanyId);
        hashMap.put("jieDuan", jieDuan);
        List<XfgcTabulation> innerTabulationList = xfgcTabulationService.getListLogic(hashMap, null);

        // 按name属性分组
        Map<String, List<XfgcTabulation>> nameType1List = innerTabulationList.stream()
                .collect(Collectors.groupingBy(XfgcTabulation::getNameType1));

        List<Map<String, Object>> mapList = new ArrayList<>();
        Integer indexName = 0;
        for (Map.Entry<String, List<XfgcTabulation>> item : nameType1List.entrySet()) {
            indexName++;
            String nameType1 = item.getKey();
            List<XfgcTabulation> value = item.getValue();

            XfgcTabulation newT = xfgcTabulationService.calculationSubtotal(value);
            value.add(0, newT);

            Map<String, Object> tempTabulation = new HashMap<>();
            tempTabulation.put("indexName", indexName);
            tempTabulation.put("nameType1", nameType1);
            tempTabulation.put("value", value);
            mapList.add(tempTabulation);
        }
        return R.ok(mapList);
    }

    @ApiOperation(value = "消防工程-查询供应商增补信息", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getZengBuList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getZengBuList(String params, Integer page, Integer size, String sortJsonStr) {
        Result<List<XfgcTabulation>> result = super.query(params, page, size, sortJsonStr);
        List<XfgcTabulation> list = result.getData();
        if (list.size() > 0) {
            //查询标底清单的增补清单内容
            List<XfgcBidBaseTabulation> bidBaseTabulationList = xfgcBidBaseTabulationService.getRepository().getZengBuList(list.get(0).getXfgcBiddingCompany().getProject().getId());
            for (XfgcTabulation p : list) {
                boolean isHave = false;
                for (XfgcBidBaseTabulation bidBaseTabulation : bidBaseTabulationList) {
                    if (p.getCodeNumber().equals(bidBaseTabulation.getCodeNumber())) {
                        isHave = true;
                    }
                }
                //标底中不存在的标记为true
                if (!isHave){
                    p.setIsBidBase(true);
                }
            }
        }

        Result result1 = new Result();
        result1.setData(list);
        result1.setCode(result.getCode());
        result1.setMessage(result.getMessage());
        result1.setPage(result.getPage());
        result1.setTotalElements(result.getTotalElements());
        result1.setTotalPage(result.getTotalPage());
        result1.setException(result.exception);
        return result1;
    }


}
